package _5thread;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * @description:
 * @author: wang zhen
 * @create: 2022-06-09 15:54
 */
public class ForkJoinTest {

    public static void main(String[] args) {

        try {

            ForkJoinTask task=new ForkJoinTask(1,1000);

            // 这是Fork/Join框架的线程池
            ForkJoinPool pool = new ForkJoinPool();
            long currentTimeMillis = System.currentTimeMillis();
            java.util.concurrent.ForkJoinTask<Integer> submit = pool.submit(task);

            Integer result = submit.get();
            long currentTimeMillis2 = System.currentTimeMillis();
            System.out.println("结果:" + result+",耗时:"+(currentTimeMillis2-currentTimeMillis));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class ForkJoinTask extends RecursiveTask<Integer> {
    int start=1;
    int end=100;

    int granularity=50;//拆分粒度



    public ForkJoinTask(int start,int end){
        this.start=start;
        this.end=end;
    }

    @Override
    protected Integer compute() {

        if(end-start<=granularity){
            int count=0;
            for(int i=start;i<=end;i++){
                count+=i;
            }

            return count;
        }


        ForkJoinTask task1=new ForkJoinTask(start,start+granularity);
        task1.fork();

        ForkJoinTask task2=new ForkJoinTask(start+granularity+1,end);
        task2.fork();
        return task1.join()+task2.join();
    }
}
